package com.mht.book.operation.impl;

import com.mht.book.entity.book.Book;
import com.mht.book.entity.book.BookList;
import com.mht.book.operation.Operations;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author wangfusheng
 * @version 1.0.0
 * @ClassName DeleteOperation.java
 * @Description 删除图书
 * @createTime 2022/12/3 13:40
 */
public class DeleteOperation implements Operations {
    @Override
    public void work(BookList bookList) {
        System.out.println("下架图书！");
        System.out.println("请输入想要下架的图书名称：");
        Scanner sc = new Scanner(System.in);
        String inputName = sc.nextLine();
        Book[] books = Arrays.copyOf(bookList.getBooks(),bookList.getUsedSize());
        //遍历书架中图书数组，查找是否存在要删除的图书信息
        //遍历时，应该遍历的长度为数组中的实际存储数据的长度，而不是数组的初始化长度
        for (int i = 0; i < bookList.getUsedSize()-1; i++) {
            String bookName = bookList.getBooks()[i].getName();
            if(Objects.equals(inputName,bookName)){
                System.out.println("已找到您想要下架的图书，正在删除...");
                //循环书籍信息，将角标数据进行置换，用后面角标的数据替换前一个角标的数据
                for (int j = i; j < bookList.getUsedSize()-1; j++) {
                    books[j] = books[j+1];
                }
                //将最后一个角标置为null
                bookList.getBooks()[bookList.getUsedSize() -1] = null;
                bookList.setBooks(books);
                bookList.setUsedSize(bookList.getUsedSize()-1);
                System.out.println("该图书已被成功下架！");
                System.out.println();
                return;
            }
        }
        System.out.println("对不起，书架中没有您要下架的图书信息！");
        System.out.println();
    }
//测试方法是否正确
//    public static void main(String[] args) {
//        DeleteOperation del = new DeleteOperation();
//        del.work(new BookList());
//    }
}
